package edu.xidian.sselab.cloudcourse.repository;

import edu.xidian.sselab.cloudcourse.domain.test1_entity;
import edu.xidian.sselab.cloudcourse.hbase.HbaseClient;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class test1_Repository {

    private static final String table_name = "monthSales"; //需要查询的Hbase表

    private final HbaseClient hbaseClient;

    @Autowired
    public test1_Repository(HbaseClient hbaseClient){
        this.hbaseClient = hbaseClient;
    }

    //start_time开始时间，end_time结束时间
    public List<test1_entity> find(String start_time,String end_time) throws IOException {
        List<test1_entity> records = new ArrayList<>();
        hbaseClient.getConnection();
        Table table = hbaseClient.getTableByName(table_name);
        FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL); //交集，必须符合每个过滤器

        RowFilter rowFilter1 = new RowFilter( //过滤器，RowFilter行键过滤器
                CompareFilter.CompareOp.GREATER_OR_EQUAL,
                new BinaryComparator(Bytes.toBytes(start_time))); //BinaryComparator，类似于字符串比较大小

        RowFilter rowFilter2 = new RowFilter(
                CompareFilter.CompareOp.LESS_OR_EQUAL,
                new BinaryComparator(Bytes.toBytes(end_time)));

        filterList.addFilter(rowFilter1); //将过滤器添加到过滤器列表中
        filterList.addFilter(rowFilter2);

        Scan scan = new Scan(); //执行根据filter的扫描操作
        if (filterList.getFilters().size() != 0) {
            scan.setFilter(filterList);
        }
        ResultScanner rs;
        try {
            if (table != null) {
                rs = table.getScanner(scan);
                for (Result result : rs) { //每个Result实体代表查询的一条数据，即一行（Row）
                    test1_entity temp = new test1_entity().map(result); //将原始的数据映射为对应的Java类
                    records.add(temp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("查询出错，返回一个空的列表!");
        }
        table.close();
        hbaseClient.closeConnection();
        return records;
    }
}
